<template>
  <div class="container">
    <div>
      <van-icon name="wap-home-o" class="icon" />
      <label class="name">当前仓库：{{warehouseName}}</label>
    </div>
    <van-button plain type="info" class="set-button" :disabled="warehouseList.length<2" @click="handleSetup">{{cpButtonText}}</van-button>
    <van-action-sheet
      v-model="selectVisible"
      :actions="cpActions"
      @select="handleSelected"
      get-container="body" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      warehouseName: '未设置',
      warehouseId: '',
      warehouseList: [],
    }
  },
  props: {
    value: Object,
    selectVisible: {Boolean, default: false}
  },
  created() {
    this.$ajax.get('/base/user_warehouse/getByCurrentUser').then(res => {
      if (res.code == 0) {
        this.warehouseList = res.data || []
        let  warehouse = null
        if (this.warehouseList.length == 1) {
          warehouse = this.warehouseList[0]
        } else {
          warehouse = this.warehouseList.find(item => item.id == sessionStorage.getItem('warehouseId'))
        }
        if (!warehouse && this.warehouseList.length > 1) {
          // this.selectVisible = true
        }
        this.setCurrent(warehouse)
      }
    })
  },
  computed: {
    cpButtonText() {
      return this.warehouseId ? '更改' : '设置'
    },
    cpActions() {
      return this.warehouseList.map(o => {
        return {
          name: o.warehouseName
        }
      })
    }
  },
  methods: {
    handleSetup() {
      this.selectVisible = true
    },
    handleSelected(item) {
      this.setCurrent(item)
      this.selectVisible = false
    },
    setCurrent(warehouse) {
      if (!warehouse) {
        warehouse = { id: '', name: '未配置' }
      }
      this.warehouseId = warehouse.id
      this.warehouseName = warehouse.name
      this.$store.commit('SET_CURRENT_WAREHOUSE', warehouse)
    }
  }
}
</script>
<style lang="scss" scoped>
  $line-height:24px;
  .container {
    opacity: 0.8;
    padding:5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .icon {
    margin: 5px;
    font-size: 18px;
    color:#444444;
  }
  .name {
    font-size:18px;
    color: #444444;
  }
  .set-button {
    margin:5px 5px 5px 20px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
  }

</style>
